package com.liyunc.demo.base.component;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
import javax.swing.WindowConstants;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class JToggleButtonExample {
    public static void main(String[] args) {
        JFrame jf = new JFrame("测试窗口");
        jf.setSize(250, 250);
        jf.setLocationRelativeTo(null);
        jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        JPanel panel = new JPanel();

        //创建开关按钮
        JToggleButton jToggleButton1 = new JToggleButton("开关1");
        JToggleButton jToggleButton2 = new JToggleButton();

        jToggleButton2.setBorderPainted(false);//不绘制按钮边框

        //设置选中和未选中的状态
        jToggleButton2.setSelectedIcon(new ImageIcon("res/img_2.png"));
        jToggleButton2.setIcon(new ImageIcon("res/img_1.png"));

        jToggleButton1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 获取事件源（即开关按钮本身）
                JToggleButton toggleBtn = (JToggleButton) e.getSource();
                System.out.println(toggleBtn.getText() + " 是否选中: " + toggleBtn.isSelected());
            }
        });
        jToggleButton2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 获取事件源（即开关按钮本身）
                JToggleButton toggleBtn = (JToggleButton) e.getSource();
                System.out.println("开关2 是否选中: " + toggleBtn.isSelected());
            }
        });

        panel.add(jToggleButton1);
        panel.add(jToggleButton2);

        jf.setContentPane(panel);
        jf.setVisible(true);
    }
}
